package com.itheima.reggie.excoption;

import com.itheima.reggie.common.R;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;


//全局异常捕获处理
@RestControllerAdvice
public class GlobalExceptionHandler {

    //定义方法,用来捕捉数据库的异常
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R handleSQLException(SQLIntegrityConstraintViolationException e) {
        //1.捕获异常信息
        String message = e.getMessage();
        System.out.println("获取异常信息:" + message);

        //2.判断是否包含重复性的约束
        if (message.contains("Duplicate entry")) {
            String msg = message.split(" ")[2];
            return R.error(msg + "用户已存在!"); //将重复信息切割响应数据
        }
        return R.error("未知错误!");
    }



}
